<?php
/*
  +----------------------------------------------------------------------+
  | content_check.php                                           |
  +----------------------------------------------------------------------+
  | Copyright (c) 2010 snda.com - Web Development Center                 |
  +----------------------------------------------------------------------+
  | Sensitive  info Check  API                                              |      
  +----------------------------------------------------------------------+
  | Authors: sebrina <zhangliyuan@snda.com>                              |      
  +----------------------------------------------------------------------+
  接口使用规则：
  1 checkSensitiveWord() 检测是否包含敏感词
  2 addContentIntoCheckDB 根据审核结果入信息审核db库
*/
  

require_once(dirname(__FILE__).'/../../config/checkinfo/UCConfCheckInfo.php');
require_once(dirname(__FILE__).'/../../libraries/PDOFactory.class.php');
require_once(dirname(__FILE__).'/../../libraries/UCLibCache.php');

define('MEMCACHE_CHECK_WORDS_ARRAY','SENCITIVE_WORDS_INFO_0'); //cache中存放敏感词组信息的key
define('MCACHE_CHECKINFO_CHANNEL_NAME','checkINFO'); //memcache分配的频道名
define('PDO_CHECK_WORD_TAGNAME','checkwords'); //pdo 的标签号
define('MCACHE_WORDS_EXPIRE_TIME',60*30);//敏感词组的过期时间
define('CHECK_MSG_QUEUE_ID',20456); //审核信息的队列号

/**
 * @purpose:检测是否包含有敏感词...
 *
 * @param string $table_name 频道名
 * @param string content 要审核的内容
 * @param string  $member_name 用户帐号
 * @return array("method" => "none",'content'="") 
 *  method  none:表示无敏感词，forbid:表示有高敏词，uncheck:表示有低敏词		
 */
function checkSensitiveWord($content)
{	
	if(empty($content)){
		$check_result['method'] = 'none';
		return $check_result;
	}
	$check_result['content'] = $content;

	$current_method = 0;  //初始化处理方式
	$current_order = 0;
	checkContentInit($content);//提取中英文字符，过滤其他干扰符号
	$ret = getSensitiveWords(); //获取敏感词和忽略词
	if(!empty($ret)){
		foreach ($ret as $row){
			if($row['word_grade']== 1){//高危敏感词
				$high_ret[] = stringToLower($row['word_text']);
			}else{
				$low_ret[] = stringToLower($row['word_text']);
			}
		}
		$find_high = findWordsInString($content,$high_ret);
		if($find_high){ //含有高危敏感词
			$check_result['method'] = 'forbid';
			return $check_result;
		}
		$find_low = findWordsInString($content,$low_ret);
		if($find_low){ //含有低危敏感词
			$check_result['method'] = 'uncheck';
			return $check_result;
		}
		$check_result['method'] = 'none';
		return $check_result;
	}else {
		$check_result['method'] = 'none';
		return $check_result;
	}
}

/**
 * @purpose:在一个字符串中查找是否包含word_arr 中的词...
 *
 * @param string  $content 要检测的内容字符串
 * @param array  $word_arr 敏感词数组
 * @return false-不包含 true-包含
 */
function findWordsInString($content,$word_arr)
{
	foreach($word_arr as $key => $value){           
		if($value != '' && strpos($content,$value)){//有包含关键字
			return true;
		}
	}
	return false;	
}

/**
 * @purpose:审核前的初始化工作:提取字符串中的中英文字符，去除其他的字符.
 * @param unknown_type $content
 * @return string content
 */
function checkContentInit(&$content)
{  
	$full_char = array('！','＂','＃','￥','％','＆','＇','（','）','＊','＋','，','－','．','／','０','１','２','３','４','５','６','７','８','９','：','；','＜','＝','＞','？','＠','Ａ','Ｂ','Ｃ','Ｄ','Ｅ','Ｆ','Ｇ','Ｈ','Ｉ','Ｊ','Ｋ','Ｌ','Ｍ','Ｎ','Ｏ','Ｐ','Ｑ','Ｒ','Ｓ','Ｔ','Ｕ','Ｖ','Ｗ','Ｘ','Ｙ','Ｚ','［','＼','］','＾','＿','｀','ａ','ｂ','ｃ','ｄ','ｅ','ｆ','ｇ','ｈ','ｉ','ｊ','ｋ','ｌ','ｍ','ｎ','ｏ','ｐ','ｑ','ｒ','ｓ','ｔ','ｕ','ｖ','ｗ','ｘ','ｙ','ｚ','｛','｜','｝','￣','　','。');
	$half_char = array('!','"','#','$','%','&',"'",'(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','[','\\',']','','_','','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~','','.');
	
	$content = str_replace($full_char,$half_char,$content);//全角符号变成半角符号
	$content = stringToLower($content); //大写变小写
	preg_match_all("/[\x{4e00}-\x{9fa5}a-zA-Z]/u",$content,$match);//提取中英文字符
	if(is_array($match[0]) && count(($match[0]) > 0)){
		$content = join("",$match[0]);
	}
}

/**
 * @purpose:转换某个字符串为小写..
 * @return  string
 */
function stringToLower($str)
{
	 return str_replace(
			array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'),
			array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'),
			$str
			);
}


/**
 * @purpose:从cache中或者DB中获取敏感字符集...
 * @return array()
 */
function getSensitiveWords()
{
	$cache = new UCLibCache(MCACHE_CHECKINFO_CHANNEL_NAME);
	$words = $cache->read(MEMCACHE_CHECK_WORDS_ARRAY);
	$cache->close();
	if (!$words) {
		 $pdo = PDOFactory::getPDO(PDO_CHECK_WORD_TAGNAME,'');
		 $words  = $pdo ->query_with_prepare("select * from $pdo->database.$pdo->table",array());
		 if(!$words){
			return false;
		}else{
			$cache->write(MEMCACHE_CHECK_WORDS_ARRAY,$words, MCACHE_WORDS_EXPIRE_TIME);
			$cache->close();
		}
	}
	return $words;
}


/**
 * 将信息添加入信息审核库中...
 *
 * @param string  $channel_name 频道名:记录twitter，评论comment，或者头像photo
 * @param string  $user 用户帐号
 * @param string  $release_time 发表的时间
 * @param string  $check_result 检测返回的结果数组,包括，content,mothod
 * @param string  $key  调用方传入的值，方便审核后台传回该参数，调用方根据该值进行相关处理
 * @return false 失败 true 成功
 */
function  addContentIntoCheckDB($channel_name,$user,$release_time,$check_result,$key="")
{
	
	if( empty($channel_name) || empty($user)||empty($check_result['content'])|| empty($check_result['method']))
	{
		return false;
	}
	$msg_info = array();	
	$msg_info['user_id'] = stringToLower($user);
	$msg_info['content'] = $check_result['content'];
	$msg_info['add_time'] = empty($release_time)?date('Y-m-d H:i:s',time()):$release_time; 
	$msg_info['key'] = $key;
	//处理方式对应表 0已通过、1未审核、2已隔离、3已删除'
	$method_array	= array(
		 "delete"=>3		//已删除
		,"forbid"=>2		//高危，已隔离
		,"uncheck"=>1		//低危、待审核
		,"none"=>0			// 通过
	);
	$msg_info['status'] = 0;
	if (array_key_exists($check_result['method'], $method_array)) {
		$msg_info['status'] = $method_array[$check_result['method']];
	}
	
	/*****************根据channel_name找到对应的db库，放入消息队列中，然后后台脚本进行入库操作*******************/

	//定义各个频道分配的序号
	$type_arr = array(
					'twitter'=>101,
					'comment'=>102,
					'photo'=>103,
				);
	
	if(isset($type_arr[$channel_name])){
		$msg_info['channel_name'] = intval($type_arr[$channel_name]);
	}else{
		return false;
	}

	$insert_info['chnanelName'] = $channel_name;
	$insert_info['msg'] = $msg_info;
	/*if(pushCheckInfoIntoQueue($insert_info)){
		echo "\n pushCheckInfoIntoQueue success:";
		return ture;
	}else{
		echo "\n pushCheckInfoIntoQueue failed:";
		return false;
	}*/
	
}

/**
 * @purpose: 审核信息入消息处理队列
 * @params : msg:需要入消息的数组信息
 * @return :  true 成功，false 失败
 */
function pushCheckInfoIntoQueue($msg){
	 $msg_queue = msg_get_queue(CHECK_MSG_QUEUE_ID);//任意分配的队列号
	 $errorcode ='';
	 if(!msg_send($msg_queue, 1, $msg, true, false, $errorcode)){
		return false;
	 }
	return true; 
}

    
/************************测试代码************************************************/   
 $content ="那我陪尾盘慰问金涉黄##【为就【为接口` 与 ^【为就【我饿【为金额为就【wepwejpwe 法轮功jpwe jpwe we wejew[ we盛大，在线ok。！";
$check_result = checkSensitiveWord($content);
var_dump($check_result);
exit;
$channel_name ='twitter';
$user ='eeeeee';
$release_time =date('Y-m-d H:i:s');
$mood_id ='3701447493128536eb9ea434e11f805a';
$tag_key ='新年,魔兽世界';
$mood ='开心';
$key ="$user|$mood_id|$mood|$tag_key";
$ret = addContentIntoCheckDB($channel_name,$user,$release_time,$check_result,$key);
var_dump($ret);

		